#!coding:utf-8
'''
Created on Oct 17, 2012

@author: join
'''
from lottery_terminal.common import utils
import datetime
from lottery_terminal.models import Period
import logging
from lottery_terminal.service.lotteryservice.baseService import BaseLottery
from lottery_terminal.common.ticketutil import shengxiao_dict

LOG = logging.getLogger('terminal')

@utils.render
def qushitu(req,href):
    '''趋势图展示'''
    result = {}
    now = datetime.datetime.now()
    lotterycode = '01'
    if href == 'double_anounce': #双色球公告
        pass
    elif href == 'ssc_anounce': #时时彩公告
        lotterycode = '20'

    try:
        
        plist=[]
        bcurrent=[]
        baverage=[]
        br_plist={}
        i_plist=[]
        bmax=[]
        bmax_lch=[]
        rcurrent=[]
        raverage=[]
        ri_plist=[]
        rmax=[]
        rmax_lch=[]
        byilou_list=[]
        
        allperiods=Period.objects.filter(lotterycode=lotterycode,awardtime__lt=now).order_by('-awardtime')

        for i in range(1,17):
            bmax_yilou=0 #初始最大遗漏为0
            bmax_lianchu0=rmax_lianchu0=1 #初始最大连出为1
            bmax_lianchu1=1
            bmax_lianchu=1
            i_plist=[]
            for allperiod in allperiods:
                if int(allperiod.awardcodes.split('|')[1])==i:
                    i_plist.insert(0,allperiod.periodid)


                
            if len(i_plist)>0:
                byilou_list.append(int(i_plist[0])-int(allperiods[len(allperiods)-1].periodid))
                byilou_list.append(int(i_plist[-1])-int(allperiods[0].periodid))
                bcurrent_yilou=int(allperiods[0].periodid)-int(i_plist[-1])#蓝球i的当前遗漏
                baverage_yilou=len(allperiods)/len(i_plist)#平均遗漏值
                for t in range(len(i_plist)-1): #蓝球的最大遗漏值
                    
                    yilou=int(i_plist[t+1])-int(i_plist[t])-1
                    byilou_list.append(yilou)
                    bm_yilou=int(i_plist[t+1])-int(i_plist[t])  #所有中奖的期次中两个相邻的期次之间相差的期次
                    if bm_yilou==1: #说明两个期次是相连的
                        bmax_lianchu0=bmax_lianchu0+1
                        bmax_lianchu1=bmax_lianchu0
                        if bmax_lianchu1>bmax_lianchu:
                            bmax_lianchu=bmax_lianchu1
                            
                    elif bm_yilou>1:
                        bmax_lianchu0=1
                
                byilou_list.sort()

                bmax_yilou=byilou_list[-1]
                    
            else:
                bcurrent_yilou=str(int(allperiods[0].periodid)-int(allperiods[(len(allperiods)-1)].periodid)+1)
                baverage_yilou='n' #n指该数从未中奖
                bmax_yilou=int(allperiods[0].periodid)-int(allperiods[len(allperiods)-1].periodid)+1
                bmax_lianchu=0
            
                
            bcurrent.append(bcurrent_yilou)
            baverage.append(baverage_yilou)
            bmax.append(bmax_yilou)
            bmax_lch.append(bmax_lianchu)
        
        br_plist['bcurrent_yl']= bcurrent
        br_plist['baverage_yl']=baverage
        br_plist['bmax_yl']=bmax
        br_plist['bmax_lch']=bmax_lch
        
        for j in range(1,34):
            ri_plist=[]
            rmax_yilou=0 #初始最大遗漏为0
            rmax_lianchu=1 #初始最大连出为1
            ryilou_list=[]
            for allperiod in allperiods:
                for t in range(6):
                    if int(allperiod.awardcodes.split('|')[0].split(',')[t])==j:
                        ri_plist.insert(0,allperiod.periodid)
            if len(ri_plist)>0:
                
                rcurrent_yilou=int(allperiods[0].periodid)-int(ri_plist[-1])  #当前遗漏值
                ryilou_list.append(int(ri_plist[0])-int(allperiods[len(allperiods)-1].periodid))
                ryilou_list.append(int(ri_plist[-1])-int(allperiods[0].periodid))
                raverage_yilou=len(allperiods)/len(ri_plist)#平均遗漏值
                rmax_lianchu0=1
                for n in range(len(ri_plist)-1):
                    ryilou=int(ri_plist[t+1])-int(ri_plist[t])-1
                    ryilou_list.append(ryilou)
                    rm_yilou=int(ri_plist[n+1])-int(ri_plist[n])
                    
                    if rm_yilou==1:
                        rmax_lianchu0=rmax_lianchu0+1
                        rmax_lianchu1=rmax_lianchu0
                        if rmax_lianchu1>rmax_lianchu:
                            rmax_lianchu=rmax_lianchu1
                            
                    elif rm_yilou>1:
                            rmax_lianchu0=1
                            
                ryilou_list.sort()
                rmax_yilou=ryilou_list[-1]
                
            else:
                rcurrent_yilou=str(int(allperiods[0].periodid)-int(allperiods[(len(allperiods)-1)].periodid)+1)
                raverage_yilou='n' #n指该数从未中奖
                rmax_yilou=int(allperiods[0].periodid)-int(allperiods[len(allperiods)-1].periodid)+1
                rmax_lianchu=0
                
            rcurrent.append(rcurrent_yilou)
            raverage.append(raverage_yilou)
            rmax.append(rmax_yilou)
            rmax_lch.append(rmax_lianchu)
        
        br_plist['rcurrent_yl']= rcurrent
        br_plist['raverage_yl']=raverage
        br_plist['rmax_yl']=rmax
        br_plist['rmax_lch']=rmax_lch
        
        plist.append(br_plist)   
    except Exception as e:
        LOG.exception("an exception occured in qushitu:%s"%e)  
         
    periods = Period.objects.filter(lotterycode=lotterycode,awardtime__lt=now).order_by('-awardtime')[0:8]
    baselottery = BaseLottery(lotterycode)
    for period in periods:
        if not period.awardtime or not period.poolmoney:
            baselottery.query_award_code(period.periodid)
            baselottery.query_award_money(period.periodid)
#    periods = Period.objects.filter(lotterycode=lotterycode,awardtime__lt=now).order_by('-awardtime')[0:8]
    infos = []
    first = True
    for period in periods:
        periodinfo={}
        
        periodinfo['periodid'] = period.periodid
        if lotterycode == '01' or lotterycode == '07' or lotterycode == '06':
            periodinfo['red'] = period.awardcodes.split('|')[0].split(',')

            for i in range(6):
                reda=int(periodinfo['red'][i])
                r_qian_list=range(1,reda-int(periodinfo['red'][i-1]))
                r_hou_list=range(reda+1,34)
            periodinfo['blue'] = period.awardcodes.split('|')[1]
            
            b_qian_list=range(1,int(periodinfo['blue']))
            b_hou_list=range(int(periodinfo['blue'])+1,17)
            periodinfo['blueleft']=b_qian_list
            periodinfo['blueright']=b_hou_list
            periodinfo['redleft']=r_qian_list
            periodinfo['redright']=r_hou_list
        elif lotterycode == '20' or lotterycode == '05' or lotterycode == '15':
            periodinfo['awardcodes'] = period.awardcodes.split(',')   
        periodinfo['awardtime'] = utils.convert_datetime_to_str(period.awardtime,'%Y-%m-%d %H:%M:%S')
        periodinfo['poolmoney'] = period.poolmoney
        if first:
            first = False
            result['latest'] = periodinfo
        else:
            infos.append(periodinfo)
    
   
    result['plist']=plist
    result['infos'] = infos
    return '%s.html'%href, result

@utils.render
def six_one_trend(req):
    '''6+1走势图'''
    return 'six_one_trend.html'


@utils.render
def ssc_trend(req):
    '''时时彩走势图'''
    infos = []
    og_data=[]
    avg_data=[]
    cur_data=[]
    big_data=[]
    
    last_per={}
    for i in range(4): 
        value={}
        for j in range(10): value["%s"%j]=0
        last_per["%s"% i]=value
    out_going={}
    for i in range(4): 
        value={}
        for j in range(10): value["%s"%j]=0
        out_going["%s"% i]=value
    
    count={}
    for i in range(10, 50): count['%s'%i]=[]
    out_go={}
    for i in range(10, 50): out_go['%s'%i]=[]
    data=[]
    for i in range(10, 50): data.append(count['%s'%i])
    data.reverse()
    data1=[]
    for i in range(10, 50): data1.append(out_go['%s'%i])
    data1.reverse()
    now = datetime.datetime.now()      
    periods = Period.objects.filter(lotterycode='20',awardtime__lt=now,awardcodes__isnull=False).exclude(awardcodes=' ').order_by('-awardtime')[0:8]   
    for period in periods:
        infos.append({'periodid':period.periodid,
                      'awardcodes0':str(period.awardcodes.split(',')[0]),
                      'awardcodes1':str(period.awardcodes.split(',')[1]), 
                      'awardcodes2':str(period.awardcodes.split(',')[2]),
                      'awardcodes3':str(period.awardcodes.split(',')[3]),
                      'awardcodes4':str(period.awardcodes.split(',')[4]) 
                      })
    periods1 = Period.objects.filter(lotterycode='20',awardtime__lt=now,awardcodes__isnull=False,).exclude(awardcodes=' ').order_by('-awardtime').all()
    for i in range(4):
        for period in periods1:
            for j in range(10):
                j=str(j)
                if ( j == str(period.awardcodes.split(',')[i+1])):
                    if (last_per[str(i)][j] <= 0):
                        last_per[str(i)][j]=-1
                        w=str(i+1)+str(j)
                        count[w][0:0]=[0]
                        out_going[str(i)][j]=out_going[str(i)][j]+1
                        out_go[w][0:0]=[out_going[str(i)][j]]
                    else:
                        w=str(i+1)+str(j)
                        count[w][0:0]=[0]
                        last_per[str(i)][j] = -1
                        out_going[str(i)][j]=1
                        out_go[w][0:0]=[out_going[str(i)][j]]
                    for n in range(10):
                        n=str(n)
                        w=str(i+1)+n
                        if (n != j):
                            out_go[w][0:0]=[0]
                            if (last_per[str(i)][n] == -1):
                                last_per[str(i)][n] = 1  
                            else:
                                last_per[str(i)][n] = last_per[str(i)][n] + 1 
                            count[w][0:0]=[last_per[str(i)][n]]
    
    for i in range(len(data)):      
        if len(data[i]) > 0:
            big = int(data[i][0]) 
            s = 0
            for j in range(len(data[i])):
                
                s = s+int(data[i][j])
                if big < int(data[i][j]):
                    big = int(data[i][j])
            cur = int(data[i][0])
            big_data[0:0]=[big]
            cur_data[0:0]=[cur]
        else:
            big_data[0:0]=[" "]
            cur_data[0:0]=[" "]  
    for i in range(len(data1)):      
        if len(data1[i]) > 0:
            big1 = int(data1[i][0]) 
            m=0
            for j in range(len(data1[i])):
                if big1 < int(data1[i][j]):
                    big1 = int(data1[i][j])  
                if j == 0:
                    if ( int(data1[i][0]) > 0):
                        m = m+int(data1[i][0])  
                else:
                    if (j < (len(data1[i])-1)):
                        if ((int(data1[i][j]) == 0) and (int(data1[i][j+1]) > 0)):
                            m = m+int(data1[i][j+1]) 
            avg_data[0:0]=[len(periods1)/(m+1)]                               
            og_data[0:0]=[big1]
        else:
            og_data[0:0]=[" "]  
            avg_data[0:0]=[" "]  
    result={'periods':infos,
            'avg_data':avg_data,
            'cur_data':cur_data,
            'big_data':big_data,
            'og_data':og_data,
            'per':[" " for i in range(5)]}
    return 'ssc_trend.html',result


@utils.render
def ssqqushitu(req):
    '''
    双色球走势图
    统计区间为99
    1. 先执行统计最大遗露, 最大连出, 平均遗露, 当前遗露, 共用函数 - construct_appear_matrix
    2. 计算显示区间矩阵, 共用函数 - construct_zhongjiang_matrix
    以下几种玩法都采用此做法实现
    '''
    now = datetime.datetime.now()
    periods=Period.objects.filter(lotterycode='01',awardtime__lt=now,awardcodes__isnull=False).order_by('-awardtime')[0:99]
    red_max_disappear=[]
    red_max_appear=[]
    red_avg_disappear=[]
    red_cur_disappear=[]
    
    blue_max_disappear=[]
    blue_max_appear=[]
    blue_avg_disappear=[]
    blue_cur_disappear=[]
    
    reds=[]
    blues=[]
    for period in periods:
        tmp=period.awardcodes.split('|')
        reds.append([red.zfill(2) for red in tmp[0].split(',')])
        blues.append([str(tmp[1]).zfill(2)])
    
    count=len(periods)
    if count:
        red_max_disappear, red_max_appear, red_avg_disappear, red_cur_disappear=construct_appear_matrix(reds, 33)
        blue_max_disappear, blue_max_appear, blue_avg_disappear, blue_cur_disappear=construct_appear_matrix(blues, 16)
    
    if count > 7:
        max_disappear=max([max(red_max_disappear), max(blue_max_disappear)])
        periods=periods[:max_disappear]
#    periods.reverse()
    matrix_leng=len(periods)
    
    infos=[]
    reds=[]
    blues=[]
    for period in periods:
        tmp=period.awardcodes.split('|')
        reds.append(tmp[0].split(','))
        blues.append([tmp[1]])
    if matrix_leng>0:
        red_matrix=construct_zhongjiang_matrix(reds, matrix_leng, 33)
        blue_matrix=construct_zhongjiang_matrix(blues, matrix_leng, 16)
        
#        periods.reverse()    
        if matrix_leng>7:
            red_matrix=red_matrix[:8]
            blue_matrix=blue_matrix[:8]
#        red_matrix.reverse()
#        blue_matrix.reverse()
        
    for i in range(min([matrix_leng, 7])):
        infos.append({'periodid': periods[i].periodid,
                      'red_matrix': red_matrix[i],
                      'blue_matrix': blue_matrix[i]})
        
    return 'double_qushitu.html', {'infos': infos,
                                   'red_max_disappear': red_max_disappear,
                                   'blue_max_disappear': blue_max_disappear,
                                   'red_max_appear':red_max_appear,
                                   'blue_max_appear':blue_max_appear,
                                   'red_avg_disappear':red_avg_disappear,
                                   'blue_avg_disappear':blue_avg_disappear,
                                   'red_cur_disappear':red_cur_disappear,
                                   'blue_cur_disappear':blue_cur_disappear}

@utils.render
def sscqushitu(req):
    '''
    时时彩走势图
    '''
    now = datetime.datetime.now()
    periods=Period.objects.filter(lotterycode='20',awardtime__lt=now,awardcodes__isnull=False).order_by('-awardtime')[0:99]
    first_max_disappear=[]
    first_max_appear=[]
    first_avg_disappear=[]
    first_cur_disappear=[]
    
    second_max_disappear=[]
    second_max_appear=[]
    second_avg_disappear=[]
    second_cur_disappear=[]
    
    third_max_disappear=[]
    third_max_appear=[]
    third_avg_disappear=[]
    third_cur_disappear=[]
    
    fourth_max_disappear=[]
    fourth_max_appear=[]
    fourth_avg_disappear=[]
    fourth_cur_disappear=[]
    
    fifth_max_disappear=[]
    fifth_max_appear=[]
    fifth_avg_disappear=[]
    fifth_cur_disappear=[]
    
    first_zhongjiangs=[]
    second_zhongjiangs=[]
    third_zhongjiangs=[]
    fourth_zhongjiangs=[]
    fifth_zhongjiangs=[]
    for period in periods:
        tmp=period.awardcodes.split(',')
        first_zhongjiangs.append([tmp[0].zfill(2)])
        second_zhongjiangs.append([tmp[1].zfill(2)])
        third_zhongjiangs.append([tmp[2].zfill(2)])
        fourth_zhongjiangs.append([tmp[3].zfill(2)])
        fifth_zhongjiangs.append([tmp[4].zfill(2)])
    count=len(periods)
    statistic=8
    if count:
        first_max_disappear, first_max_appear, first_avg_disappear, first_cur_disappear=construct_appear_matrix(first_zhongjiangs, 10, statistic, False)
        second_max_disappear, second_max_appear, second_avg_disappear, second_cur_disappear=construct_appear_matrix(second_zhongjiangs, 10, statistic, False)
        third_max_disappear, third_max_appear, third_avg_disappear, third_cur_disappear=construct_appear_matrix(third_zhongjiangs, 10, statistic, False)
        fourth_max_disappear, fourth_max_appear, fourth_avg_disappear, fourth_cur_disappear=construct_appear_matrix(fourth_zhongjiangs, 10, statistic, False)
        fifth_max_disappear, fifth_max_appear, fifth_avg_disappear, fifth_cur_disappear=construct_appear_matrix(fifth_zhongjiangs, 10, statistic, False)
    
    if count > statistic:
        max_disappear=max([max(first_max_disappear), max(second_max_disappear), max(third_max_disappear), max(fourth_max_disappear), max(fifth_max_disappear)])
        periods=periods[:max_disappear]
    periods.reverse()
    matrix_leng=len(periods)
    
    infos=[]
    first_zhongjiangs=[]
    second_zhongjiangs=[]
    third_zhongjiangs=[]
    fourth_zhongjiangs=[]
    fifth_zhongjiangs=[]
    for period in periods:
        tmp=period.awardcodes.split(',')
        first_zhongjiangs.append([tmp[0]])
        second_zhongjiangs.append([tmp[1]])
        third_zhongjiangs.append([tmp[2]])
        fourth_zhongjiangs.append([tmp[3]])
        fifth_zhongjiangs.append([tmp[4]])
    if matrix_leng>0:
        first_matrix=construct_zhongjiang_matrix(first_zhongjiangs, matrix_leng, 10, False)
        second_matrix=construct_zhongjiang_matrix(second_zhongjiangs, matrix_leng, 10, False)
        third_matrix=construct_zhongjiang_matrix(third_zhongjiangs, matrix_leng, 10, False)
        fourth_matrix=construct_zhongjiang_matrix(fourth_zhongjiangs, matrix_leng, 10, False)
        fifth_matrix=construct_zhongjiang_matrix(fifth_zhongjiangs, matrix_leng, 10, False)
        
        periods.reverse()    
        if matrix_leng>statistic:
            first_matrix=first_matrix[-statistic:]
            second_matrix=second_matrix[-statistic:]
            third_matrix=third_matrix[-statistic:]
            fourth_matrix=fourth_matrix[-statistic:]
            fifth_matrix=fifth_matrix[-statistic:]
        first_matrix.reverse()
        second_matrix.reverse()
        third_matrix.reverse()
        fourth_matrix.reverse()
        fifth_matrix.reverse()
        
        for i in range(min([matrix_leng, statistic])):
            infos.append({'periodid': periods[i].periodid,
                          'first_matrix': first_matrix[i],
                          'second_matrix': second_matrix[i],
                          'third_matrix': third_matrix[i],
                          'fourth_matrix': fourth_matrix[i],
                          'fifth_matrix': fifth_matrix[i],
                          })

    return 'ssc_qushitu.html', {'infos': infos,
                                   'first_max_disappear': first_max_disappear,
                                   'first_max_appear': first_max_appear,
                                   'first_avg_disappear': first_avg_disappear,
                                   'first_cur_disappear': first_cur_disappear,
                                   'second_max_disappear': second_max_disappear,
                                   'second_max_appear': second_max_appear,
                                   'second_avg_disappear': second_avg_disappear,
                                   'second_cur_disappear': second_cur_disappear,
                                   'third_max_disappear': third_max_disappear,
                                   'third_max_appear': third_max_appear,
                                   'third_avg_disappear': third_avg_disappear,
                                   'third_cur_disappear': third_cur_disappear,
                                   'fourth_max_disappear': fourth_max_disappear,
                                   'fourth_max_appear': fourth_max_appear,
                                   'fourth_avg_disappear': fourth_avg_disappear,
                                   'fourth_cur_disappear': fourth_cur_disappear,
                                   'fifth_max_disappear': fifth_max_disappear,
                                   'fifth_max_appear': fifth_max_appear,
                                   'fifth_avg_disappear': fifth_avg_disappear,
                                   'fifth_cur_disappear': fifth_cur_disappear,
                                   }


@utils.render
def fifteen_fivequshitu(req):
    '''
    15选5走势图
    '''
    now = datetime.datetime.now()
    periods=Period.objects.filter(lotterycode='15',awardtime__lt=now,awardcodes__isnull=False).order_by('-awardtime')[0:99]
    first_max_disappear=[]
    first_max_appear=[]
    first_avg_disappear=[]
    first_cur_disappear=[]

    statistic=8
        
    first_zhongjiangs=[]
    for period in periods:
        first_zhongjiangs.append([i.zfill(2) for i in period.awardcodes.split(',')])
    count=len(periods)
    if count:
        first_max_disappear, first_max_appear, first_avg_disappear, first_cur_disappear=construct_appear_matrix(first_zhongjiangs, 15, statistic)
    
    if count > statistic:
        max_disappear=max(first_max_disappear)
        periods=periods[:max_disappear]
    periods.reverse()
    matrix_leng=len(periods)
    
    infos=[]
    first_zhongjiangs=[]
    for period in periods:
        first_zhongjiangs.append([i.lstrip('0') for i in period.awardcodes.split(',')])
    if matrix_leng>0:
        first_matrix=construct_zhongjiang_matrix(first_zhongjiangs, matrix_leng, 15)
        
        periods.reverse()    
        if matrix_leng>statistic:
            first_matrix=first_matrix[-statistic:]
        first_matrix.reverse()
        
        for i in range(min([matrix_leng, statistic])):
            infos.append({'periodid': periods[i].periodid,
                          'first_matrix': first_matrix[i],
                          })
        
    return 'fifteen_five_qushitu.html', {'infos': infos,
                                   'first_max_disappear': first_max_disappear,
                                   'first_max_appear': first_max_appear,
                                   'first_avg_disappear': first_avg_disappear,
                                   'first_cur_disappear': first_cur_disappear,
                                   }


@utils.render
def fucai3Dqushitu(req):
    '''
    福彩3D走势图
    '''
    now = datetime.datetime.now()
    periods=Period.objects.filter(lotterycode='05',awardtime__lt=now,awardcodes__isnull=False).order_by('-awardtime')[0:99]
    distr_max_disappear=[]
    distr_max_appear=[]
    distr_avg_disappear=[]
    distr_cur_disappear=[]
    
    third_max_disappear=[]
    third_max_appear=[]
    third_avg_disappear=[]
    third_cur_disappear=[]
    
    second_max_disappear=[]
    second_max_appear=[]
    second_avg_disappear=[]
    second_cur_disappear=[]
    
    first_max_disappear=[]
    first_max_appear=[]
    first_avg_disappear=[]
    first_cur_disappear=[]
    
    distr_zhongjiangs=[]
    third_zhongjiangs=[]
    second_zhongjiangs=[]
    first_zhongjiangs=[]
    for period in periods:
        tmp=period.awardcodes.split(',')
        distr_zhongjiangs.append([str(red).zfill(2) for red in tmp])
        third_zhongjiangs.append([tmp[0].zfill(2)])
        second_zhongjiangs.append([tmp[1].zfill(2)])
        first_zhongjiangs.append([tmp[2].zfill(2)])
    count=len(periods)
    statistic=8
    if count:
        distr_max_disappear, distr_max_appear, distr_avg_disappear, distr_cur_disappear=construct_appear_matrix(distr_zhongjiangs, 10, statistic, False)
        third_max_disappear, third_max_appear, third_avg_disappear, third_cur_disappear=construct_appear_matrix(third_zhongjiangs, 10, statistic, False)
        second_max_disappear, second_max_appear, second_avg_disappear, second_cur_disappear=construct_appear_matrix(second_zhongjiangs, 10, statistic, False)
        first_max_disappear, first_max_appear, first_avg_disappear, first_cur_disappear=construct_appear_matrix(first_zhongjiangs, 10, statistic, False)
    
    if count > statistic:
        max_disappear=max([max(distr_max_disappear), max(third_max_disappear), max(second_max_disappear), max(first_max_disappear)])
        periods=periods[:max_disappear]
    periods.reverse()
    matrix_leng=len(periods)
    
    infos=[]
    distr_zhongjiangs=[]
    third_zhongjiangs=[]
    second_zhongjiangs=[]
    first_zhongjiangs=[]
    for period in periods:
        tmp=period.awardcodes.split(',')
        distr_zhongjiangs.append(tmp)
        third_zhongjiangs.append([tmp[0]])
        second_zhongjiangs.append([tmp[1]])
        first_zhongjiangs.append([tmp[2]])
    if matrix_leng>0:
        distr_matrix=construct_zhongjiang_matrix(distr_zhongjiangs, matrix_leng, 10, False)
        third_matrix=construct_zhongjiang_matrix(third_zhongjiangs, matrix_leng, 10, False)
        second_matrix=construct_zhongjiang_matrix(second_zhongjiangs, matrix_leng, 10, False)
        first_matrix=construct_zhongjiang_matrix(first_zhongjiangs, matrix_leng, 10, False)

        periods.reverse()    
        if matrix_leng>statistic:
            distr_matrix=distr_matrix[-statistic:]
            third_matrix=third_matrix[-statistic:]
            second_matrix=second_matrix[-statistic:]
            first_matrix=first_matrix[-statistic:]
        distr_matrix.reverse()
        third_matrix.reverse()
        second_matrix.reverse()
        first_matrix.reverse()
        
        for i in range(min([matrix_leng, statistic])):
            infos.append({'periodid': periods[i].periodid,
                          'distr_matrix': distr_matrix[i],
                          'third_matrix': third_matrix[i],
                          'second_matrix': second_matrix[i],
                          'first_matrix': first_matrix[i]})
        
    return 'fucai3D_qushitu.html', {'infos': infos,
                                    'distr_max_disappear': distr_max_disappear,
                                   'distr_max_appear': distr_max_appear,
                                   'distr_avg_disappear': distr_avg_disappear,
                                   'distr_cur_disappear': distr_cur_disappear,
                                   'third_max_disappear': third_max_disappear,
                                   'third_max_appear': third_max_appear,
                                   'third_avg_disappear': third_avg_disappear,
                                   'third_cur_disappear': third_cur_disappear,
                                   'second_max_disappear': second_max_disappear,
                                   'second_max_appear': second_max_appear,
                                   'second_avg_disappear': second_avg_disappear,
                                   'second_cur_disappear': second_cur_disappear,
                                   'first_max_disappear': first_max_disappear,
                                   'first_max_appear': first_max_appear,
                                   'first_avg_disappear': first_avg_disappear,
                                   'first_cur_disappear': first_cur_disappear}


@utils.render
def qilecaiqushitu(req):
    '''
    7乐彩走势图
    '''
    now = datetime.datetime.now()
    periods=Period.objects.filter(lotterycode='07',awardtime__lt=now,awardcodes__isnull=False).order_by('-awardtime')[0:99]
    red_max_disappear=[]
    red_max_appear=[]
    red_avg_disappear=[]
    red_cur_disappear=[]
    
    statistic=8
    
    reds=[]
    for period in periods:
        tmp=period.awardcodes.split('|')
        reds.append([str(red).zfill(2) for red in tmp[0].split(',')])
    print reds
    count=len(periods)
    if count:
        red_max_disappear, red_max_appear, red_avg_disappear, red_cur_disappear=construct_appear_matrix(reds, 30, statistic)
    
    if count > statistic:
        max_disappear=max(red_max_disappear)
        periods=periods[:max_disappear]
    periods.reverse()
    matrix_leng=len(periods)
    
    infos=[]
    reds=[]
    for period in periods:
        tmp=period.awardcodes.split('|')
        reds.append(tmp[0].split(','))
    if matrix_leng>0:
        red_matrix=construct_zhongjiang_matrix(reds, matrix_leng, 30)
        
        periods.reverse()    
        if matrix_leng>statistic:
            red_matrix=red_matrix[-statistic:]
        red_matrix.reverse()
        
        for i in range(min([matrix_leng, statistic])):
            tmp=periods[i].awardcodes.split('|')
            infos.append({'periodid': periods[i].periodid,
                          'red_awards': tmp[0].split(','),
                          'special_code': tmp[1], 
                          'red_matrix': red_matrix[i]})
        
    return 'qilecai_qushitu.html', {'infos': infos,
                                   'red_max_disappear': red_max_disappear,
                                   'red_max_appear':red_max_appear,
                                   'red_avg_disappear':red_avg_disappear,
                                   'red_cur_disappear':red_cur_disappear}


@utils.render
def six_onequshitu(req):
    '''
    东方6+1走势图
    '''
    now = datetime.datetime.now()
    periods=Period.objects.filter(lotterycode='06',awardtime__lt=now,awardcodes__isnull=False).order_by('-awardtime')[0:99]
    
    first_max_disappear=[]
    first_max_appear=[]
    first_avg_disappear=[]
    first_cur_disappear=[]
    
    second_max_disappear=[]
    second_max_appear=[]
    second_avg_disappear=[]
    second_cur_disappear=[]
    
    third_max_disappear=[]
    third_max_appear=[]
    third_avg_disappear=[]
    third_cur_disappear=[]
    
    fourth_max_disappear=[]
    fourth_max_appear=[]
    fourth_avg_disappear=[]
    fourth_cur_disappear=[]
    
    fifth_max_disappear=[]
    fifth_max_appear=[]
    fifth_avg_disappear=[]
    fifth_cur_disappear=[]
    
    sixth_max_disappear=[]
    sixth_max_appear=[]
    sixth_avg_disappear=[]
    sixth_cur_disappear=[]
    
    statistic=8
    
    first_zhongjiangs=[]
    second_zhongjiangs=[]
    third_zhongjiangs=[]
    fourth_zhongjiangs=[]
    fifth_zhongjiangs=[]
    sixth_zhongjiangs=[]
    for period in periods:
        tmp=period.awardcodes.split('|')
        awards=tmp[0].split(',')
        awards=[i for i in awards]
        first_zhongjiangs.append(awards[0].zfill(2))
        second_zhongjiangs.append(awards[1].zfill(2))
        third_zhongjiangs.append(awards[2].zfill(2))
        fourth_zhongjiangs.append(awards[3].zfill(2))
        fifth_zhongjiangs.append(awards[4].zfill(2))
        sixth_zhongjiangs.append(awards[5].zfill(2))
    count=len(periods)
    if count:
        first_max_disappear, first_max_appear, first_avg_disappear, first_cur_disappear=construct_appear_matrix(first_zhongjiangs, 10, statistic,False)
        second_max_disappear, second_max_appear, second_avg_disappear, second_cur_disappear=construct_appear_matrix(second_zhongjiangs, 10, statistic,False)
        third_max_disappear, third_max_appear, third_avg_disappear, third_cur_disappear=construct_appear_matrix(third_zhongjiangs, 10, statistic,False)
        fourth_max_disappear, fourth_max_appear, fourth_avg_disappear, fourth_cur_disappear=construct_appear_matrix(fourth_zhongjiangs, 10, statistic,False)
        fifth_max_disappear, fifth_max_appear, fifth_avg_disappear, fifth_cur_disappear=construct_appear_matrix(fifth_zhongjiangs, 10, statistic,False)
        sixth_max_disappear, sixth_max_appear, sixth_avg_disappear, sixth_cur_disappear=construct_appear_matrix(sixth_zhongjiangs, 10, statistic,False)
    
    if count > statistic:
        max_disappear=max([max(first_max_disappear), max(second_max_disappear), max(third_max_disappear), max(fourth_max_disappear), max(fifth_max_disappear), max(sixth_max_disappear)])
        periods=periods[:max_disappear]
    periods.reverse()
    matrix_leng=len(periods)
    
    infos=[]
    first_zhongjiangs=[]
    second_zhongjiangs=[]
    third_zhongjiangs=[]
    fourth_zhongjiangs=[]
    fifth_zhongjiangs=[]
    sixth_zhongjiangs=[]
    for period in periods:
        tmp=period.awardcodes.split('|')
        awards=tmp[0].split(',')
        awards=[i for i in awards]
        first_zhongjiangs.append(awards[0])
        second_zhongjiangs.append(awards[1])
        third_zhongjiangs.append(awards[2])
        fourth_zhongjiangs.append(awards[3])
        fifth_zhongjiangs.append(awards[4])
        sixth_zhongjiangs.append(awards[5])
        
    if matrix_leng>0:
        first_matrix=construct_zhongjiang_matrix(first_zhongjiangs, matrix_leng, 10,False) #TODO:FALSE
        second_matrix=construct_zhongjiang_matrix(second_zhongjiangs, matrix_leng, 10,False)
        print '+++++++++++++++++++++++'
        print second_zhongjiangs
        print second_matrix
        print '+++++++++++++++++++++++'
        third_matrix=construct_zhongjiang_matrix(third_zhongjiangs, matrix_leng, 10,False)
        fourth_matrix=construct_zhongjiang_matrix(fourth_zhongjiangs, matrix_leng, 10,False)
        fifth_matrix=construct_zhongjiang_matrix(fifth_zhongjiangs, matrix_leng, 10,False)
        sixth_matrix=construct_zhongjiang_matrix(sixth_zhongjiangs, matrix_leng, 10,False)

        periods.reverse()    
        if matrix_leng>statistic:
            first_matrix=first_matrix[-statistic:]
            second_matrix=second_matrix[-statistic:]
            third_matrix=third_matrix[-statistic:]
            fourth_matrix=fourth_matrix[-statistic:]
            fifth_matrix=fifth_matrix[-statistic:]
            sixth_matrix=sixth_matrix[-statistic:]
        first_matrix.reverse()
        second_matrix.reverse()
        third_matrix.reverse()
        fourth_matrix.reverse()
        fifth_matrix.reverse()
        sixth_matrix.reverse()
        
        for i in range(min([matrix_leng, statistic])):
            print second_matrix[i]
            tmp=periods[i].awardcodes.split('|')
            awards=tmp[0].split(',')
            awards=[award for award in awards]
            infos.append({'periodid': periods[i].periodid,
                          'awards': awards,
                          'special_code': shengxiao_dict.get(tmp[1]),
                          'first_matrix': first_matrix[i],
                          'second_matrix': second_matrix[i],
                          'third_matrix': third_matrix[i],
                          'fourth_matrix': fourth_matrix[i],
                          'fifth_matrix': fifth_matrix[i],
                          'sixth_matrix': sixth_matrix[i]
                         })
        
    return 'six_one_qushitu.html', {'infos': infos,
                                   'first_max_disappear': first_max_disappear,
                                   'first_max_appear': first_max_appear,
                                   'first_avg_disappear': first_avg_disappear,
                                   'first_cur_disappear': first_cur_disappear,
                                   'second_max_disappear': second_max_disappear,
                                   'second_max_appear': second_max_appear,
                                   'second_avg_disappear': second_avg_disappear,
                                   'second_cur_disappear': second_cur_disappear,
                                   'third_max_disappear': third_max_disappear,
                                   'third_max_appear': third_max_appear,
                                   'third_avg_disappear': third_avg_disappear,
                                   'third_cur_disappear': third_cur_disappear,
                                   'fourth_max_disappear': fourth_max_disappear,
                                   'fourth_max_appear': fourth_max_appear,
                                   'fourth_avg_disappear': fourth_avg_disappear,
                                   'fourth_cur_disappear': fourth_cur_disappear,
                                   'fifth_max_disappear': fifth_max_disappear,
                                   'fifth_max_appear': fifth_max_appear,
                                   'fifth_avg_disappear': fifth_avg_disappear,
                                   'fifth_cur_disappear': fifth_cur_disappear,
                                   'sixth_max_disappear': sixth_max_disappear,
                                   'sixth_max_appear': sixth_max_appear,
                                   'sixth_avg_disappear': sixth_avg_disappear,
                                   'sixth_cur_disappear': sixth_cur_disappear,
                                   }


def construct_appear_matrix(zhongjiang_matrix_list, row_leng, statistic=7, start_from_1=True):
    '''
    @param zhongjiang_matrix_list: 中奖二维数组
    @param row_leng: 行数  
    @param start_from_1: 中奖号码是否从1开始, 否则从0开始
    '''
    return_max_disappear=[0 for i in range(row_leng)]
    return_max_appear=[0 for i in range(row_leng)]
    return_avg_disappear=[0 for i in range(row_leng)]
    return_cur_disappear=[0 for i in range(row_leng)]
    for i in range(1, row_leng+1):
        indx=[]
        for j in zhongjiang_matrix_list:
            if str(i if start_from_1 else i-1).zfill(2) in j: indx.append(True)
            else: indx.append(False)
        max_disappear, max_appear, avg_disappear, cur_disappear=qushistatistic(indx, statistic)
        column=i-1
        return_max_disappear[column]=max_disappear
        return_max_appear[column]=max_appear
        return_avg_disappear[column]=avg_disappear
        return_cur_disappear[column]=cur_disappear
    
    return return_max_disappear, return_max_appear, return_avg_disappear, return_cur_disappear

def construct_zhongjiang_matrix(zhongjiang_matrix_list, row_leng, column_leng, start_from_1=True):
    '''
    @param zhongjiang_matrix_list: 中奖二维数组
    @param row_leng: 行数
    @param column_leng: 列数
    @param start_from_1: 中奖号码是否从1开始, 否则从0开始  
    根据中奖二维数组, 构造中奖和遗漏二维数组?
    '''
    return_matrix=[ [{'zhongjiang':False, 'value':0} for i in range(column_leng)] for i in range(row_leng)]
    for i in zhongjiang_matrix_list[0]: # 中奖
        indx=int(i)-1 if start_from_1 else int(i)
        if indx>column_leng: continue
        return_matrix[0][indx]['zhongjiang']=True
        return_matrix[0][indx]['value']=int(i)
    for column in range(column_leng): # 没中奖
        if not return_matrix[0][column]['zhongjiang']: return_matrix[0][column]['value']=1
        
    for row in range(1, row_leng):
        for column in zhongjiang_matrix_list[row]: # 中奖
            indx=int(column)-1 if start_from_1 else int(column)
            return_matrix[row][indx]['zhongjiang']=True
            return_matrix[row][indx]['value']=int(column)
        for column in range(column_leng): # 没中奖
            if not return_matrix[row][column]['zhongjiang']:
                return_matrix[row][column]['value']=1 if return_matrix[row-1][column]['zhongjiang'] else return_matrix[row-1][column]['value']+1
    return return_matrix
        
def qushistatistic(l, cur=7):
    '''
    【最大遗漏期数】某统计项在统计期数内最多遗漏的期数
    【最大连出期数】某统计项在统计期数内最多连续出现的期数
    【平均遗漏期数】某统计项在统计期数内遗漏期数总和除以出现次数
    【当前遗漏期数】某统计项自上期开出到本期间隔的期数
    '''
    count=len(l)
    max_disappear=0
    max_appear=0
    avg_disappear=0
    cur_disappear=0
    
    appear_list=[i for i in range(count) if l[i]]
    disappear_list=[i for i in range(count) if not l[i]]
    
    if disappear_list:
        append=False
        if disappear_list[0]: 
            disappear_list.insert(0, 0)
            append=True 
        tmp_appear_list=[]
        point=disappear_list[0]
        for i in range(1, len(disappear_list)):
            tmp_appear_list.append(disappear_list[i]-point-1)
            point=disappear_list[i]
        tmp_appear_list.append(count-disappear_list[-1]-1)
        if append: 
            tmp_appear_list[0]+=1
            disappear_list=appear_list[1:]
        
        max_appear=max(tmp_appear_list)
    else:
        max_appear=count
    
    if appear_list:
        appear_size=len(appear_list)
        append=False
        if appear_list[0]: 
            appear_list.insert(0, 0)
            append=True
        tmp_disappear_list=[]
        point=appear_list[0]
        for i in range(1, len(appear_list)):
            tmp_disappear_list.append(appear_list[i]-point-1)
            point=appear_list[i]
        tmp_disappear_list.append(count-appear_list[-1]-1)
        if append: 
            tmp_disappear_list[0]+=1
            appear_list=appear_list[1:]
        
        max_disappear=max(tmp_disappear_list)
        avg_disappear=sum(tmp_disappear_list)/appear_size
    else:
        max_disappear=count
        avg_disappear=count
        cur_disappear=count
    
    if count>cur and appear_list:
        cur_disappear=appear_list[0]
        
    return max_disappear, max_appear, avg_disappear, cur_disappear

